import React, { useEffect, useState } from 'react';
import { Button, Divider, List, Popconfirm, Tabs, Typography } from 'antd';
import {
  bowOutTeam,
  deleteApplyTeam,
  listApplyTeam,
  listGetQueryTeam,
  listGetTeam,
} from '@/services/teamService';
import { message, Space, Tag } from 'antd/es';
import { useModel } from '@umijs/max';
import QueryUserTeam from '@/pages/team/list/components/QueryUserTeam';
import UpdateCureTeam from '@/pages/team/list/components/UpdateCureTeam';
import UpdateTeam from '@/pages/team/list/components/UpdateTeam';
import ApplyTeam from '@/pages/team/list/components/ApplyTeam';
import { applyDeleteTeam, getApplyTeam } from '@/services/applyService';
import { TeamType } from '@/models/team';
import { ApplyType } from '@/models/apply';

/**
 *  退出队伍
 * @param userId
 * @param teamId
 */
const doBowOutTeam = async (userId: number, teamId: number) => {
  const hide = message.loading('正在退出');
  if (!userId || !teamId) return 1;
  try {
    const res = await bowOutTeam({
      userId: userId,
      teamId: teamId,
    });
    message.success('退出成功');
    return res.data;
  } catch (e: any) {
    message.error('退出失败，' + e.message);
  } finally {
    hide();
  }
};

/**
 *  删除创建队伍申请
 * @param fields
 */
const deleteApply = async (fields: TeamType.TeamDeleteApplyRequest) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteApplyTeam({
      teamId: fields.teamId,
    });
    message.success('删除成功');
    return res.data;
  } catch (e: any) {
    message.error('删除失败，' + e.message);
  } finally {
    hide();
  }
};

/**
 *  删除加入队伍申请
 * @param params
 */
const deleteJoinApply = async (params: ApplyType.ApplyDeleteTeamRequest) => {
  const hide = message.loading('正在删除');
  try {
    const res = await applyDeleteTeam({
      ...params,
    });
    message.success('删除成功');
    return res.data;
  } catch (e: any) {
    message.error('删除失败，' + e.message);
  } finally {
    hide();
  }
};

const TeamListPage: React.FC<unknown> = () => {
  const [teamGetList, setTeamGetList] = useState<TeamType.TeamVo[]>([]);
  const [teamGetListQuery, setTeamGetListQuery] = useState<TeamType.TeamVo[]>(
    [],
  );
  const [teamGetListApply, setTeamGetListApply] = useState<TeamType.TeamVo[]>(
    [],
  );
  const [teamJoinGetListApply, setTeamJoinGetListApply] = useState<
    TeamType.TeamVo[]
  >([]);

  const [QueryModalVisible, setQueryModalVisible] = useState<boolean>(false);
  const [ApplyModalVisible, setApplyModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const initSearchParams: TeamType.TeamVo = {};

  const [updateData, setUpdateData] =
    useState<TeamType.TeamVo>(initSearchParams);
  const [updateCureModalVisible, setUpdateCureModalVisible] =
    useState<boolean>(false);
  const [updateCureData, setUpdateCureData] =
    useState<TeamType.TeamVo>(initSearchParams);
  const [allMember, setAllMember] = useState<number>(0);
  const [applyMember, setApplyMember] = useState<number>(0);
  const [total] = useState<number>(0);

  const [loading, setLoading] = useState<boolean>(true);
  const { initialState } = useModel('@@initialState');
  const tagMap = initialState?.tagMap;
  const loginUser = initialState?.loginUser;

  const allVisible = (id: number) => {
    if (!id) {
      return [];
    }
    setAllMember(id);
    setQueryModalVisible(true);
  };
  const applyVisible = (id: number) => {
    if (!id) {
      return [];
    }
    setApplyMember(id);
    setApplyModalVisible(true);
  };

  const updateVisble = (teamVo: TeamType.TeamVo) => {
    if (!teamVo) {
      return [];
    }
    setUpdateData(teamVo);
    setUpdateModalVisible(true);
  };

  const updateCureVisble = (teamVo: TeamType.TeamVo) => {
    if (!teamVo) {
      return [];
    }
    setUpdateCureData(teamVo);
    setUpdateCureModalVisible(true);
  };

  // 加载数据
  useEffect(() => {
    setLoading(true);
    listGetTeam()
      .then((res) => {
        // @ts-ignore
        setTeamGetList(res.data);
      })
      .catch((e: any) => {
        message.error('加载失败，' + e.message);
      })
      .finally(() => setLoading(false));
    listGetQueryTeam()
      .then((res) => {
        // @ts-ignore
        setTeamGetListQuery(res.data);
      })
      .catch((e: any) => {
        message.error('加载失败，' + e.message);
      })
      .finally(() => setLoading(false));
    listApplyTeam()
      .then((res) => {
        // @ts-ignore
        setTeamGetListApply(res.data);
      })
      .catch((e: any) => {
        message.error('加载失败，' + e.message);
      })
      .finally(() => setLoading(false));
    getApplyTeam({
      userId: loginUser?.id || 0,
      applyReviewStatus: 0,
    })
      .then((res) => {
        setTeamJoinGetListApply(res.data);
      })
      .catch((e: any) => {
        message.error('加载失败，' + e.message);
      })
      .finally(() => setLoading(false));
  }, []);

  return (
    <div
      style={{
        background: '#F5F7FA',
      }}
    >
      <Tabs>
        <Tabs.TabPane tab="加入的队伍" key="item-1">
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              total,
            }}
            loading={loading}
            dataSource={teamGetList}
            renderItem={(teamVo, index) => (
              <List.Item
                key={index}
                extra={
                  // todo 但图片无效时，则转成默认的图片
                  <img
                    height={240}
                    src={
                      teamVo?.teamAvatarUrl ||
                      'https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/9226/logo/nothingImg.jpg'
                    }
                  />
                }
              >
                <Space direction="vertical">
                  <div style={{ marginBottom: '1em' }}>
                    队伍名称:<Tag>{teamVo.teamName}</Tag>
                    <br />
                    项目已有人数/最多人数:
                    <Tag>
                      {teamVo.minNum}/{teamVo.maxNum}
                    </Tag>
                    <br />
                    类型：<Tag>{teamVo.teamType}</Tag>
                    <br />
                    技术：<Tag>{teamVo.teamTechnologyType}</Tag>
                  </div>
                  <Typography.Paragraph
                    ellipsis={{ rows: 7, expandable: true, symbol: '展开' }}
                  >
                    简介:{teamVo.teamDescription}
                  </Typography.Paragraph>
                </Space>
                <br />
                <Space
                  split={<Divider type="vertical" />}
                  style={{ fontSize: 14 }}
                >
                  <Typography.Text type="secondary">
                    创建时间:{teamVo?.createTime?.toString().split('T')[0]}
                  </Typography.Text>
                  <Button
                    type="primary"
                    onClick={() => allVisible(teamVo?.id || 0)}
                  >
                    查看队伍信息
                  </Button>
                  <Button type="primary" onClick={() => updateVisble(teamVo)}>
                    修改基础信息
                  </Button>
                  <Button
                    type="primary"
                    style={{
                      display:
                        loginUser?.id !== teamVo.userId ? 'none' : 'block',
                    }}
                    onClick={() => applyVisible(teamVo?.id || 0)}
                  >
                    申请列表
                  </Button>
                  {teamVo.cureStatus === 1 ? (
                    <Button
                      type="primary"
                      disabled
                      onClick={() => updateCureVisble(teamVo)}
                    >
                      带审核状态
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      onClick={() => updateCureVisble(teamVo)}
                    >
                      修改公开信息
                    </Button>
                  )}
                  {loginUser?.id === teamVo.userId ? (
                    <Popconfirm
                      title="您确定要解散队伍吗？"
                      onConfirm={() =>
                        doBowOutTeam(loginUser?.id || 0, teamVo?.id || 0)
                      }
                      okText="确认"
                      cancelText="取消"
                    >
                      <Typography.Link type="danger">解散队伍</Typography.Link>
                    </Popconfirm>
                  ) : (
                    <Popconfirm
                      title="您确定要退出队伍吗？"
                      onConfirm={() =>
                        doBowOutTeam(loginUser?.id || 0, teamVo?.id || 0)
                      }
                      okText="确认"
                      cancelText="取消"
                    >
                      <Typography.Link type="danger">退出队伍</Typography.Link>
                    </Popconfirm>
                  )}
                </Space>
              </List.Item>
            )}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab="自己创建的队伍" key="item-2">
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              total,
            }}
            loading={loading}
            dataSource={teamGetListQuery}
            renderItem={(teamVo, index) => (
              <List.Item
                key={index}
                extra={
                  <img
                    height={240}
                    src={
                      teamVo?.teamAvatarUrl ||
                      'https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/9226/logo/nothingImg.jpg'
                    }
                  />
                }
              >
                <Space direction="vertical">
                  <div style={{ marginBottom: '1em' }}>
                    队伍名称:<Tag>{teamVo.teamName}</Tag>
                    <br />
                    项目已有人数/最多人数:
                    <Tag>
                      {teamVo.minNum}/{teamVo.maxNum}
                    </Tag>
                    <br />
                    类型：<Tag>{teamVo.teamType}</Tag>
                    <br />
                    技术：<Tag>{teamVo.teamTechnologyType}</Tag>
                  </div>
                  <Typography.Paragraph
                    ellipsis={{ rows: 7, expandable: true, symbol: '展开' }}
                  >
                    简介:{teamVo.teamDescription}
                  </Typography.Paragraph>
                </Space>
                <br />
                <Space
                  split={<Divider type="vertical" />}
                  style={{ fontSize: 14 }}
                >
                  <Typography.Text type="secondary">
                    创建时间:{teamVo?.createTime?.toString().split('T')[0]}
                  </Typography.Text>
                  <Button
                    type="primary"
                    onClick={() => allVisible(teamVo?.id || 0)}
                  >
                    查看队伍信息
                  </Button>
                  <Button type="primary" onClick={() => updateVisble(teamVo)}>
                    修改基础信息
                  </Button>
                  <Button
                    type="primary"
                    style={{
                      display:
                        loginUser?.id !== teamVo.userId ? 'none' : 'block',
                    }}
                    onClick={() => applyVisible(teamVo?.id || 0)}
                  >
                    申请列表
                  </Button>
                  {teamVo.cureStatus === 1 ? (
                    <Button
                      type="primary"
                      disabled
                      onClick={() => updateCureVisble(teamVo)}
                    >
                      带审核状态
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      onClick={() => updateCureVisble(teamVo)}
                    >
                      修改公开信息
                    </Button>
                  )}
                  {loginUser?.id === teamVo.userId ? (
                    <Popconfirm
                      title="您确定要解散队伍吗？"
                      onConfirm={() =>
                        doBowOutTeam(loginUser?.id || 0, teamVo?.id || 0)
                      }
                      okText="确认"
                      cancelText="取消"
                    >
                      <Typography.Link type="danger">解散队伍</Typography.Link>
                    </Popconfirm>
                  ) : (
                    <Popconfirm
                      title="您确定要退出队伍吗？"
                      onConfirm={() =>
                        doBowOutTeam(loginUser?.id || 0, teamVo?.id || 0)
                      }
                      okText="确认"
                      cancelText="取消"
                    >
                      <Typography.Link type="danger">退出队伍</Typography.Link>
                    </Popconfirm>
                  )}
                </Space>
              </List.Item>
            )}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab="创建队伍申请中" key="item-3">
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              total,
            }}
            loading={loading}
            dataSource={teamGetListApply}
            renderItem={(teamVo, index) => (
              <List.Item
                key={index}
                extra={
                  <img
                    height={240}
                    src={
                      teamVo?.teamAvatarUrl ||
                      'https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/9226/logo/nothingImg.jpg'
                    }
                  />
                }
              >
                <Space direction="vertical">
                  <div style={{ marginBottom: '1em' }}>
                    队伍名称:<Tag>{teamVo.teamName}</Tag>
                    <br />
                    项目已有人数/最多人数:
                    <Tag>
                      {teamVo.minNum}/{teamVo.maxNum}
                    </Tag>
                    <br />
                    类型：<Tag>{teamVo.teamType}</Tag>
                    <br />
                    技术：<Tag>{teamVo.teamTechnologyType}</Tag>
                  </div>
                  <Typography.Paragraph
                    ellipsis={{ rows: 7, expandable: true, symbol: '展开' }}
                  >
                    简介:{teamVo.teamDescription}
                  </Typography.Paragraph>
                </Space>
                <br />
                <Space
                  split={<Divider type="vertical" />}
                  style={{ fontSize: 14 }}
                >
                  <Typography.Text type="secondary">
                    创建时间:{teamVo?.createTime?.toString().split('T')[0]}
                  </Typography.Text>
                  <Popconfirm
                    title="您确定要删除申请吗？"
                    onConfirm={() =>
                      deleteApply({
                        teamId: teamVo?.id || 0,
                      })
                    }
                    okText="确认"
                    cancelText="取消"
                  >
                    <Typography.Link type="danger">删除申请</Typography.Link>
                  </Popconfirm>
                </Space>
              </List.Item>
            )}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab="加入队伍申请" key="item-4">
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              total,
            }}
            loading={loading}
            dataSource={teamJoinGetListApply}
            renderItem={(teamVo, index) => (
              <List.Item
                key={index}
                extra={
                  <img
                    height={240}
                    src={
                      teamVo?.teamAvatarUrl ||
                      'https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/9226/logo/nothingImg.jpg'
                    }
                  />
                }
              >
                <Space direction="vertical">
                  <div style={{ marginBottom: '1em' }}>
                    队伍的id:
                    <Tag>{teamVo.id}</Tag>
                    <br />
                  </div>
                  <Typography.Paragraph
                    ellipsis={{ rows: 7, expandable: true, symbol: '展开' }}
                  >
                    简介:
                    {
                      // @ts-ignore
                      teamVo.applyContent
                    }
                  </Typography.Paragraph>
                </Space>
                <br />
                <Space
                  split={<Divider type="vertical" />}
                  style={{ fontSize: 14 }}
                >
                  <Typography.Text type="secondary">
                    申请的时间:{teamVo?.createTime?.toString().split('T')[0]}
                  </Typography.Text>
                  <Popconfirm
                    title="您确定要删除申请吗？"
                    onConfirm={() =>
                      deleteJoinApply({
                        // @ts-ignore
                        id: teamVo.id,
                        userId: teamVo.userId,
                      })
                    }
                    okText="确认"
                    cancelText="取消"
                  >
                    <Typography.Link type="danger">删除申请</Typography.Link>
                  </Popconfirm>
                </Space>
              </List.Item>
            )}
          />
        </Tabs.TabPane>
      </Tabs>
      <QueryUserTeam
        modalVisible={QueryModalVisible}
        onSubmit={() => {}}
        allMember={allMember}
        // @ts-ignore
        loginUser={loginUser}
        onCancel={() => setQueryModalVisible(false)}
      />
      <UpdateCureTeam
        oldData={updateCureData}
        modalVisible={updateCureModalVisible}
        onSubmit={() => {}}
        // @ts-ignore
        loginUser={loginUser}
        onCancel={() => setUpdateCureModalVisible(false)}
      />
      <UpdateTeam
        oldData={updateData}
        modalVisible={updateModalVisible}
        onSubmit={() => {}}
        // @ts-ignore
        loginUser={loginUser}
        // @ts-ignore
        tagMap={tagMap}
        onCancel={() => setUpdateModalVisible(false)}
      />
      <ApplyTeam
        modalVisible={ApplyModalVisible}
        onSubmit={() => {}}
        allMember={applyMember}
        // @ts-ignore
        loginUser={loginUser}
        onCancel={() => setApplyModalVisible(false)}
      />
    </div>
  );
};
//
export default TeamListPage;
